package com.fyfeng.touchtest;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;

import com.fyfeng.touchtest.RefreshListView.OnRefreshListener;

public class MainActivity extends Activity {

	private static final String tag = MainActivity.class.getSimpleName();

	private MyHandler mHandler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mHandler = new MyHandler(this);
		
		final RefreshListView mrlayout = (RefreshListView) this.findViewById(R.id.view);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, this.getData());
		mrlayout.setAdapter(adapter);

		mrlayout.setOnRefreshListener(new OnRefreshListener(){

			@Override
			public void onRefresh() {
				
				new Thread(new Runnable(){

					@Override
					public void run() {
						Log.d(tag, "开始刷新数据 ...");
						try {
							Thread.sleep(1000 * 3);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						Log.d(tag, "数据刷新完毕.");
						Message msg = Message.obtain();
						msg.what = 101;
						mHandler.sendMessage(msg);
						
					}}).start();
				
			}});
		
		Log.d(tag, "列表数据设置完毕。");
	}

	private void endRefresh(){
		final RefreshListView mrlayout = (RefreshListView) this.findViewById(R.id.view);
		mrlayout.refreshCompleted();
	}
	
	static class MyHandler extends Handler{
		private MainActivity activity;
		
		public MyHandler(MainActivity activity){
			this.activity = activity;
		}
		@Override
		public void handleMessage(Message msg) {
			if(101 == msg.what){
				activity.endRefresh();
			}
		}
	}
	
	
	private List<String> getData() {

		List<String> list = new ArrayList<String>();

		for (int k = 0; k < 20; k++) {
			list.add("测试 - " + k);
		}

		return list;

	}
}
